package com.yupi.yupao.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.data.redis.RedisSessionRepository;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

import java.time.Duration;

/**
 * 会话配置类
 * 实现Redis宕机时的会话降级策略
 */
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 2592000, 
        redisNamespace = "yupao:session")
public class SessionConfig {

    /**
     * 配置Cookie序列化器
     */
    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("YUPAO_SESSION");
        serializer.setCookiePath("/");
        serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
        // 设置Cookie的最大存活时间为30天
        serializer.setCookieMaxAge(2592000);
        return serializer;
    }

    /**
     * 配置Redis连接工厂，添加故障转移机制
     */
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
        redisConfig.setHostName("localhost");
        redisConfig.setPort(6379);
        redisConfig.setDatabase(1);
        
        // 创建Jedis连接工厂
        JedisConnectionFactory factory = new JedisConnectionFactory(redisConfig);
        
        // 设置连接超时时间
        factory.setTimeout(1000); // 1秒超时
        
        return factory;
    }
} 